package com.dhr.tx.service.impl;

import com.dhr.tx.bean.UserPo;
import com.dhr.tx.orm.UserMapper;
import com.dhr.tx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description:
 * @className: UserServiceImpl
 * @package: com.tx.service.impl
 * @author: duanhr@hsyuntai.com
 * @date: 2019/3/7 16:54
 * @copyright: 版权归 HSYUNTAI 所有
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    //    @Transactional
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, timeout = 3)
    @Override
    public void methodA(UserPo userPo) {

//        userMapper.restInsert(userPo);

//        System.out.println(1/0);
//        直接調用B方法
//        this.methodB(userPo);

//        調用B方法並鋪貨異常
//        try {
//            this.methodB(userPo);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

//        使A不變，B事物生效
//        ((UserService) AopContext.currentProxy()).methodB(userPo);


        saveAndUpdate(userPo);
//        throw new RuntimeException("主动抛出异常-测试事物回滚状态!");

    }

    //    @Transactional
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void methodB(UserPo userPo) {
        try {
            System.out.println("MethodB" + Transactional.class.getName());
            //年龄加一
            userMapper.restUpdate(new UserPo(userPo.getUserId(), null, new AtomicInteger(userPo.getAge()).incrementAndGet()));
            //修改姓名
            userMapper.restUpdate(new UserPo(userPo.getUserId(), userPo.getUserName() + "_" + new AtomicInteger(userPo.getAge()).incrementAndGet(), null));
        } catch (RuntimeException e) {
            throw new RuntimeException("主动抛出异常-测试事物回滚状态!");
        } catch (Exception e) {
            throw e;

        }
    }


    protected void saveAndUpdate(UserPo userPo) {
        userMapper.restInsert(userPo);
        //超時回滾
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        userMapper.restUpdate(new UserPo(userPo.getUserId(), null, new AtomicInteger(userPo.getAge()).incrementAndGet()));
    }

}
